<template>
  <div class="page-container">
    <div class="page-header">
      <button class="back-button" @click="goToHome">
        <span class="icon-arrow-left"></span>
        返回首页
      </button>
      <h1>自定义报表</h1>
      <p>创建和导出符合特定需求的报表</p>
    </div>
    
    <div class="report-builder">
      <div class="report-options">
        <h2>报表设置</h2>
        
        <div class="form-group">
          <label>报表名称</label>
          <input type="text" v-model="reportName" placeholder="输入报表名称">
        </div>
        
        <div class="form-group">
          <label>时间范围</label>
          <div class="date-range">
            <input type="date" v-model="startDate">
            <span class="range-separator">至</span>
            <input type="date" v-model="endDate">
          </div>
        </div>
        
        <div class="form-group">
          <label>数据维度</label>
          <div class="checkbox-group">
            <label class="checkbox-item">
              <input type="checkbox" v-model="dimensions" value="ticketType"> 工单类型
            </label>
            <label class="checkbox-item">
              <input type="checkbox" v-model="dimensions" value="priority"> 优先级
            </label>
            <label class="checkbox-item">
              <input type="checkbox" v-model="dimensions" value="department"> 处理部门
            </label>
            <label class="checkbox-item">
              <input type="checkbox" v-model="dimensions" value="status"> 工单状态
            </label>
            <label class="checkbox-item">
              <input type="checkbox" v-model="dimensions" value="requester"> 申请人
            </label>
          </div>
        </div>
        
        <div class="form-group">
          <label>指标选择</label>
          <div class="checkbox-group">
            <label class="checkbox-item">
              <input type="checkbox" v-model="metrics" value="count"> 工单数量
            </label>
            <label class="checkbox-item">
              <input type="checkbox" v-model="metrics" value="responseTime"> 响应时间
            </label>
            <label class="checkbox-item">
              <input type="checkbox" v-model="metrics" value="resolveTime"> 解决时间
            </label>
            <label class="checkbox-item">
              <input type="checkbox" v-model="metrics" value="satisfaction"> 满意度评分
            </label>
          </div>
        </div>
        
        <div class="form-group">
          <label>导出格式</label>
          <select v-model="exportFormat">
            <option value="pdf">PDF</option>
            <option value="excel">Excel</option>
            <option value="csv">CSV</option>
            <option value="json">JSON</option>
          </select>
        </div>
        
        <div class="action-buttons">
          <button class="btn-preview" @click="previewReport">预览报表</button>
          <button class="btn-generate" @click="generateReport">生成并导出</button>
        </div>
      </div>
      
      <div class="report-preview">
        <h2>报表预览</h2>
        <div class="preview-container" v-if="showPreview">
          <div class="preview-header">
            <h3>{{ reportName || '自定义报表' }}</h3>
            <div class="preview-date">
              {{ formatDate(startDate) }} 至 {{ formatDate(endDate) }}
            </div>
          </div>
          
          <div class="preview-content">
            <!-- 图表预览 -->
            <div ref="reportChart" class="report-chart"></div>
            
            <table class="report-table">
              <thead>
                <tr>
                  <th>工单类型</th>
                  <th>数量</th>
                  <th>平均响应时间</th>
                  <th>平均解决时间</th>
                  <th>满意度</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>网络问题</td>
                  <td>128</td>
                  <td>15分钟</td>
                  <td>3.2小时</td>
                  <td>4.6</td>
                </tr>
                <tr>
                  <td>硬件故障</td>
                  <td>76</td>
                  <td>22分钟</td>
                  <td>5.8小时</td>
                  <td>4.3</td>
                </tr>
                <tr>
                  <td>软件请求</td>
                  <td>94</td>
                  <td>10分钟</td>
                  <td>2.5小时</td>
                  <td>4.8</td>
                </tr>
                <tr class="total-row">
                  <td>总计</td>
                  <td>298</td>
                  <td>15.7分钟</td>
                  <td>3.8小时</td>
                  <td>4.6</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        
        <div class="no-preview" v-else>
          <p>设置报表参数并点击"预览报表"查看效果</p>
        </div>
      </div>
    </div>
    
    <div class="saved-reports">
      <h2>保存的报表模板</h2>
      <div class="report-templates">
        <div class="template-card" v-for="(template, index) in savedTemplates" :key="index">
          <div class="template-name">{{ template.name }}</div>
          <div class="template-desc">{{ template.description }}</div>
          <div class="template-actions">
            <button @click="useTemplate(template)">使用</button>
            <button @click="deleteTemplate(index)">删除</button>
          </div>
        </div>
      </div>
      <button class="btn-save-template" @click="saveAsTemplate">保存为模板</button>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'CustomReports',
  data() {
    return {
      reportName: '',
      startDate: this.formatDate(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)),
      endDate: this.formatDate(new Date()),
      dimensions: ['ticketType'],
      metrics: ['count', 'responseTime', 'resolveTime'],
      exportFormat: 'excel',
      showPreview: false,
      savedTemplates: [
        {
          name: '月度工单总结',
          description: '包含工单数量、响应时间和解决时间的月度报表'
        },
        {
          name: '部门绩效报表',
          description: '按部门统计的工单处理效率报表'
        }
      ],
      reportChart: null
    };
  },
  methods: {
    goToHome() {
      this.$router.push('/home');
    },
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return d.toISOString().split('T')[0];
    },
    // 初始化报表图表
    initReportChart() {
      const chartDom = this.$refs.reportChart
      if (!chartDom) return
      
      // 销毁已有实例
      if (this.reportChart) {
        this.reportChart.dispose()
      }
      
      this.reportChart = echarts.init(chartDom)
      
      // 根据选择的指标动态生成图表
      const series = []
      if (this.metrics.includes('count')) {
        series.push({
          name: '工单数量',
          type: 'bar',
          data: [128, 76, 94],
          itemStyle: { color: '#3498db' }
        })
      }
      
      if (this.metrics.includes('resolveTime')) {
        series.push({
          name: '平均解决时间(小时)',
          type: 'line',
          yAxisIndex: 1,
          data: [3.2, 5.8, 2.5],
          symbol: 'circle',
          itemStyle: { color: '#e74c3c' },
          lineStyle: { color: '#e74c3c' }
        })
      }
      
      const option = {
        tooltip: { trigger: 'axis' },
        legend: { top: 0 },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: {
          type: 'category',
          data: ['网络问题', '硬件故障', '软件请求']
        },
        yAxis: [
          {
            type: 'value',
            name: '数量',
            min: 0
          },
          {
            type: 'value',
            name: '时间(小时)',
            min: 0,
            position: 'right'
          }
        ],
        series: series
      }
      
      this.reportChart.setOption(option)
    },
    previewReport() {
      this.showPreview = true;
      // 延迟初始化图表，确保DOM已渲染
      this.$nextTick(() => {
        this.initReportChart()
      })
    },
    generateReport() {
      alert(`报表 "${this.reportName}" 已生成并以 ${this.exportFormat} 格式导出`);
    },
    saveAsTemplate() {
      if (!this.reportName) {
        alert('请输入报表名称');
        return;
      }
      this.savedTemplates.push({
        name: this.reportName,
        description: `自定义报表 (${this.formatDate(this.startDate)} 至 ${this.formatDate(this.endDate)})`
      });
      alert('已保存为模板');
    },
    useTemplate(template) {
      this.reportName = template.name;
      this.showPreview = false;
    },
    deleteTemplate(index) {
      this.savedTemplates.splice(index, 1);
    }
  },
  watch: {
    // 当指标变化时重新渲染图表
    metrics() {
      if (this.showPreview) {
        this.initReportChart()
      }
    }
  },
  mounted() {
    window.addEventListener('resize', () => {
      if (this.reportChart) {
        this.reportChart.resize()
      }
    })
  },
  beforeUnmount() {
    if (this.reportChart) {
      this.reportChart.dispose()
    }
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 30px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 20px;
  font-weight: 500;
}

.back-button:hover {
  background: #2980b9;
  transform: translateY(-2px);
}

.report-builder {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.report-options, .report-preview {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input[type="text"],
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e1e5e8;
  border-radius: 5px;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-range input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e1e5e8;
  border-radius: 5px;
}

.range-separator {
  color: #666;
}

.checkbox-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 30px;
}

.btn-preview, .btn-generate, .btn-save-template {
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s;
}

.btn-preview {
  background: #f1f5f9;
  color: #333;
}

.btn-preview:hover {
  background: #e2e8f0;
}

.btn-generate {
  background: #3498db;
  color: white;
}

.btn-generate:hover {
  background: #2980b9;
}

.preview-container {
  border: 1px solid #e1e5e8;
  border-radius: 5px;
  padding: 20px;
}

.preview-header {
  text-align: center;
  margin-bottom: 20px;
}

.preview-header h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.preview-date {
  color: #666;
  font-size: 14px;
}

.report-chart {
  width: 100%;
  height: 300px;
  margin-bottom: 20px;
}

.report-table {
  width: 100%;
  border-collapse: collapse;
}

.report-table th, .report-table td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #e1e5e8;
}

.report-table th {
  background-color: #f8f9fa;
  font-weight: 500;
}

.total-row {
  background-color: #f1f5f9;
  font-weight: bold;
}

.no-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
  background: #f8f9fa;
  border-radius: 5px;
  color: #888;
}

.saved-reports {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.saved-reports h2 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
}

.report-templates {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.template-card {
  padding: 15px;
  border: 1px solid #e1e5e8;
  border-radius: 5px;
  transition: all 0.3s;
}

.template-card:hover {
  border-color: #3498db;
  box-shadow: 0 2px 8px rgba(52, 152, 219, 0.1);
}

.template-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.template-desc {
  font-size: 13px;
  color: #666;
  margin-bottom: 10px;
}

.template-actions {
  display: flex;
  gap: 5px;
}

.template-actions button {
  padding: 5px 10px;
  border: none;
  border-radius: 3px;
  font-size: 12px;
  cursor: pointer;
}

.template-actions button:first-child {
  background: #3498db;
  color: white;
}

.template-actions button:last-child {
  background: #f8f9fa;
  color: #e74c3c;
}

.btn-save-template {
  background: #2ecc71;
  color: white;
}

.btn-save-template:hover {
  background: #27ae60;
}
</style>